#pragma once
#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <sys/ipc.h>
 #include "comm.hpp"

#define PATHNAME "."
#define PROJ_ID 0x67
#define SIZE 4096
#define CREAT "creat"
#define USER "user"

using namespace std;

class Shm
{
private:
    void CreatHelper(int Opt)
    {
        _shmid = shmget(_key, SIZE, Opt); 
        if(_shmid < 0)
            ERR_EXIT("shmget");
        printf("shmid:%d\n", _shmid);
    }

    void Creat() //创建全新的共享内存并设置权限
    {
        CreatHelper(IPC_CREAT | IPC_EXCL | 0666);
    }

    void Get() //获取共享内存
    {
        CreatHelper(IPC_CREAT);
    }

    void Attach()
    {
        _start_mem = shmat(_shmid, NULL, 0);
        if((long long)_start_mem < 0)
            ERR_EXIT("shmat");
        printf("Attach success\n");
    }

    void Detach() //去关联
    {
        int n = shmdt(_start_mem);
        if(n < 0)
            ERR_EXIT("shmdt");
        printf("Detach success\n");
    }

    void Destroy()
    {
        Detach(); //不管是谁都要去关联
        if(_usertype == CREAT) //只有创建者需要销毁
        {
            if(_shmid >= 0)
            {
                int n = shmctl(_shmid, IPC_RMID, nullptr);
                if(n < 0)
                    ERR_EXIT("shmctl");
                printf("shm:%d 删除成功\n", _shmid);
            }
        }
        
    }

public:
    Shm(const string &pathname, int projid, const string &usertype)
        :_shmid(-1)
        , _size(SIZE)
        , _start_mem(nullptr)
        ,_pathname(pathname)
        ,_projid(projid)
        ,_usertype(usertype)
    {
        _key = ftok(PATHNAME, PROJ_ID);
        if(_key < 0)
            ERR_EXIT("ftok");
        printf("key:0x%x\n", _key); 
        if(usertype == CREAT) 
            Creat();
        else if(usertype == USER)
            Get();
      //  Attach(); //挂载
    }

    void* VirtualAdd()
    {
        printf("virtual add:%p\n", _start_mem);
        return _start_mem;
    }

    void Attr()
    {
        struct shmid_ds ds;
        shmctl(_shmid, IPC_STAT, &ds);
        printf("shm_segsz:%ld\n", ds.shm_segsz);
        printf("__key:0x%x\n", ds.shm_perm.__key);
    }

    ~Shm()
    {    
        Destroy();
    }

private:
    key_t _key;
    int _shmid;
    size_t _size;
    void* _start_mem; 
    string _pathname;
    int _projid;
    string _usertype;
};